<template>
  <div class="app-container clearfix">
    <!-- 列表 -->
    <piaomake-table
      :department-all-list-data="departmentAllListData"
      :invoice-company-all-list-data="invoiceCompanyAllListData"
      :data="listData"
      :search-params="searchKey"
      :total-count="totalCount"
      :list-loading="listLoading"
      :type="type"
      :id="id"
      :dept-name="deptName"
      :params-data="paramsData"
      :form-data="formData"
      :invoice-type-options="invoiceTypeOptions"
      @on-save="handleSave"
      @on-approve="handleApprove"
      @on-export="handleExport"
      @on-init="handleInitList"
      @on-edit="handleEditShow"></piaomake-table>

  </div>
</template>

<script>
  import {
    getPiaoListAPI,
    getPiaoListUpdateAPI,
    savePiaomakeAPI,
    submitApproveAPI,
    deleteApproveAPI,
    getInvoiceTreeAPI,
    drawbackAPI
  } from '@/api/todo/piaomake'
  import { piaomakeTable } from './components'
  import { formatDate, formatTimestamp } from '@/utils/utils'
  import commonMixins from '@/mixins/common'
  import treeAllListData from '@/mixins/treeAllListData'
  import salaryImportExcel from '@/mixins/salaryImportExcel'
  import filters from '@/filters/filters'
  import request from '@/utils/request'

  export default {
    name: 'PiaomakeList',
    mixins: [commonMixins, filters, treeAllListData, salaryImportExcel],
    components: {
      piaomakeTable,
      
    },
    data() {
      return {
        invoiceTypeOptions:[],
        invoiceTree:[],
      	paramsData:{},
        type: '1', // 1、新增 2、修改 3、查看
        id: '', // 月薪列表ID
        initParams: { // 初始化参数
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页个数
          sort: '', // 排序
          
        },
        searchKey: {}, // 搜索参数
        editInfo: { // 编辑弹出框
          visible: false, // 是否显示模态框
          detailInfo: {}
        },
        totalCount: 0, // 分页用的列表总条数
        listLoading: false,
        isShowSelectParams: false, // 如果没有选择部门或者月份就显示弹出框
        deptName: '',
        importInstance: undefined,
        listData: [] // 列表数据
      }
    },
    props: {},
    computed: {},
    methods: {
      goBack() {
        this.$router.replace({
          name: 'Piao'
        })
      },
      goSalaryMake({ type, data }) { 
        let query = { type }
        if (type === '1') {
          query = {
            ...query,
            ...data
          }
        } else {
          query['id'] = data.id
        }
        this.$router.replace({
          name: 'Salarymake',
          query
        })
      },
     
      handleReelect() { // 重新选择部门和月份
        this.isShowSelectParams = true
      },
      handleEditShow(data = {}) { // 编辑－显示弹出框
        this.editInfo.visible = true
        this.editInfo.detailInfo = data
      },
      handleCreated() { // 添加成功
        this.searchKey.page = 1
        this.getListData()
      },
      handleUpdated() { // 编辑成功
        this.getListData()
      },
      handleInitList(params = {}) { // 初始化列表
        this.searchKey = {
          ...this.searchKey,
          ...params
        }
        this.getListData()
      },
      handleSave(submitData,tuipiao) { // 保存
        //console.log(submitData);
        //let params = this.formatParams(listData)
        if(!submitData.hrInvoiceDetails )submitData.hrInvoiceDetails = []
        // submitData = this.trimAll(submitData)
        // console.log(submitData)
        // return;

        //处理退票的保存 yyf
        if(tuipiao){
          let submitDataNew = {}

          console.log(submitData)

          submitDataNew.invoiceId = submitData.invoiceId;
          submitDataNew.id = submitData.id;
          submitDataNew.remark = submitData.remarkNew || submitData.remark;

          //如果invoiceId不存在，说明是新增退票
          if(!submitData.invoiceId) {
            delete submitDataNew.id;
            submitDataNew.invoiceId = submitData.id;
          }

          console.log(submitDataNew)
          

          submitDataNew.hrInvoiceRefundDetails = [];

          for(let i=0;i<submitData.hrInvoiceDetails.length;i++){
            let hrInvoiceDetail = submitData.hrInvoiceDetails[i];
            submitDataNew.hrInvoiceRefundDetails.push({
              "invoiceDetailId": hrInvoiceDetail.id,
              "remark": hrInvoiceDetail.remark,
              "status": hrInvoiceDetail.status
            });
          }

          

          request({
              url: '/hr/invoice/refund/apply/save',
              method: 'post',
              data: submitDataNew
          }).then(response => {
              if (response.code != '200') {
                  this.msgError('保存失败，原因是' + response.data.msg)
                  return
              }
              this.msgSuccess('保存成功');
              //this.goBack()
              //以修改的方式重新访问
              this.$router.push({
                name: 'Tuipiaomake',
                query:{
                    type: '2',
                    tuiPiao:true,
                    id:response.data.id,
                 
                }
              });

          })
          return;
        }
        this.saveData(submitData)
      },

      // trimAll(obj){
      //   if(obj.constructor.toString().indexOf('Object') != -1){
      //     console.log('是对象');
          
      //     for(let k in obj){
      //       if(obj[k].constructor.toString().indexOf('Array') != -1){
      //          for(let i=0;i < obj[k].length;i++){
      //           let v = obj[k][i];
      //           for(let k in v){
      //             v[k] = v[k] && v[k].toString().trim()
      //           }
      //         } 
      //       }
      //       obj[k] = obj[k] && obj[k].toString().trim()
      //     }

      //   }
      //   return v;
      // },
      
      handleApprove(submitData,tuipiao) { // 是否审批
        this.$confirm(`是否提交进入审批流程?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        //处理退票的提交 yyf
        if(tuipiao){
          let submitDataNew = {}

          console.log(submitData)
          submitDataNew.id = submitData.id;
          submitDataNew.invoiceId = submitData.invoiceId;

          if(submitDataNew.id && !submitDataNew.invoiceId){
            submitDataNew.invoiceId = submitDataNew.id
            delete submitDataNew.id
          }
          
          submitDataNew.remark = submitData.remarkNew || submitData.remark;;
          submitDataNew.hrInvoiceRefundDetails = [];

          for(let i=0;i<submitData.hrInvoiceDetails.length;i++){
            let hrInvoiceDetail = submitData.hrInvoiceDetails[i];
            submitDataNew.hrInvoiceRefundDetails.push({
              "invoiceDetailId": hrInvoiceDetail.id,
              "remark": hrInvoiceDetail.remark,
              "status": hrInvoiceDetail.status
            });
          }
          request({
              url: '/hr/invoice/refund/apply/commit',
              method: 'post',
              data: submitDataNew
          }).then(response => {
              if (response.code != '200') {
                  this.msgError('提交失败，原因是' + response.msg)
                  return
              }
              this.msgSuccess(response.msg);
              this.$store.dispatch("tagsView/delView", this.$route); 
              this.$router.push({
                name: 'Tuipiao',
                query:{
                   
                }
              });

              

          })
          return;
        }  



          if(!submitData.hrInvoiceDetails )submitData.hrInvoiceDetails = []
          this.submitApproveData(submitData)
        }).catch(() => {
        })
      },
      
      handleExport() { // 导出按钮操作
        let { id, type } = this
        if (type === '1' && !id) {
          this.$notify.error({
            title: '错误',
            message: '请先保存数据！'
          })
        } else {
          this.$confirm('是否确认导出所有数据?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async() => {
            try {
              let response = await exportListAPI({
                id
              })
              this.downloadFile(response)
            } catch (error) {
              // console.log(error)
              this.$notify.error({
                title: '错误',
                message: error.message || '操作失败！'
              })
            }
          }).catch(() => {
          })
        }
      },
      
      async submitApproveData(params) { // 审批－请求数据
        try {
          this.listLoading = true
          //alert(window.id)
          if(window.id){
            params.id = window.id; //如果是新增的情况，先保存，会回显id，审批的时候也要带上。否则，会多保存一条！
          }

          let response = await submitApproveAPI({
            ...params
          })
          let result = response
          console.log('submitApproveData');
          if (+result.code === 200) {
            this.goBack()
            this.$notify({
              title: '成功',
              message: result.msg || '审批提交成功！',
              type: 'success',
              duration: 4000
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '审批提交失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '审批提交失败！'
          })
        } finally {
          this.listLoading = false
        }
      },

      //保存表单 handleSave
      async saveData(params = {}) { // 保存－请求数据
        try {
          let { type } = this
          this.listLoading = true
          let response = await savePiaomakeAPI({
            ...params,
            ...{

            }
          })
          console.log(response);
          let result = response
          if (+result.code === 200) {
            this.$notify({
              title: '成功',
              message: '保存成功！',
              type: 'success',
              duration: 2000
            })

          console.log('反显ID'+ result.data.id);

          

          window.id =  result.data.id;

          let query = {type:2,id:result.data.id};
         
           setTimeout(()=>{
               this.$router.push({
                  name: 'Tuipiaomake',
                  query
                })
            },1000)

           // history.back()
            
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '保存失败！'
            })
            
            
          }
           
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '保存失败！'
          })
        } finally {
          this.listLoading = false
          //console.log(this.paramsData)
          
        }
      },
      async getDepartmentAllListData() { // 获取所有数据
        try {
          await this.$store.dispatch('department/GetDepartmentList', {
            request: true
          
          })
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message
          })
        }
      },
      async getListData() { // 获取列表数据
        
        try {
          let { id, type, searchKey } = this
          id = id || window.id

          this.listLoading = true
          let response = undefined
          if (type == '1') { // 

            if(id) { //用于新增后直接保存的情况
              console.log('根据id获取列表数据：' + id);
              response = await getPiaoListUpdateAPI({
                id: id
              })
            }
            
          } else { // 修改、查看获取接口
            console.log('根据id获取列表数据：' + id);
            response = await getPiaoListUpdateAPI({
              id: id
            })
          }
          let result = response
          if (+result.code === 200) {
            if (type == '1') { // 新增
              
            } else { // 修改和查看
              this.formData = result.data
            }
            
           
            
            //alert( this.paramsData.title);
            if(this.paramsData.type == 2){
              	//console.log('修改返回')
              	//console.log(this.listData[0])
              	this.paramsData.title = result.data.title;
              	this.paramsData.salaryType = result.data.salaryType;

            //  	console.log(this.paramsData);
              }

          } else if (+result.code === 500) {
            this.$router.go(-1)
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取列表失败！'
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取列表失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '获取列表失败!'
          })
        } finally {
          this.listLoading = false
        }
      },
      async initUpload() { // 初始化上传
        if (this.importInstance) this.importInstance.destroy()
        this.$nextTick(() => {
          // 导入初始化
          if (this.id || true) {
            this.initPlupload({
              container: 'import-box',
              selectFiles: 'upload-import',
              params: {
                submissionId: this.id
              }
            }).then((instance) => {
              this.importInstance = instance
              this.importInstance.init()
              this.importInstance.bind('handleAddFile', (up, result) => {
                up.splice(0, 1)
                
                this.$confirm('文档已经解析成功，是否确认导入数据?注意：导入后列表已有数据将被清空！！', '警告', {
		            confirmButtonText: '确定',
		            cancelButtonText: '取消',
		            type: 'warning'
		          }).then(async() => {
		           //清空原有数据
	                this.listData = result.data || []
	                this.totalCount = result.data.length
		          }).catch(() => {})
                
              })
            }).catch((error) => {
              this.$notify.error({
                title: '错误',
                message: error.message
              })
            })
          }
        })
      },
      async initBeforeRoute(obj, to, from) { // 初始化页面
        this.initUpload(); //初始化导入
        
        //如果是退票查看或者修改过来的，执行单独的逻辑
        if(to.query.tuiPiao){
          obj.paramsData = to.query
         return; 
        }

        let { id, type = '1', deptId, salaryDate,title,salaryType} = to.query
        console.log(to)
        obj.type = type
        obj.id = id
        obj.searchKey.deptId = deptId
        obj.searchKey.salaryDate = salaryDate
         obj.paramsData = to.query

        


         //if(window.id) window.id = ''; //页面初始化的话， 缓存的ID要删除
        
        //console.log(to.query)
        if (type == '1') { // 新增
          //alert( obj.paramsData.title);
          if (deptId && salaryDate) {
            obj.isShowSelectParams = false
            obj.getListData()
          } else {
            obj.isShowSelectParams = true
          }
          obj.getDepartmentAllListData()
        } else { // 修改、查看
          if (id) {
            obj.isShowSelectParams = false
            obj.getListData()

          } else {
            //this.$router.go(-1)
          }
        }

        

      },
      async initData() { // 初始化数据
        //this.getListData()
        this.getDepartmentAllListData()
        this.getInvoiceCompanyListData()
        let response = await getInvoiceTreeAPI({})
        this.invoiceTypeOptions = response.data;

        
      }
    },
    watch: {
      initParams: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
            this.searchKey = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      },
      isShowSelectParams(newVal, oldVal) {
        let { id, type } = this
        let { deptId, salaryDate } = this.searchKey
        if (!newVal && (!deptId || !salaryDate)) {
          this.$nextTick(() => {
            // this.isShowSelectParams = true
            // this.$notify.error({
            //   title: '错误',
            //   message: '必须要选择部门和发放月份!'
            // })
          })
        }
      }
    },
    created() {
    },
    mounted() {
      this.initData();

     
      

    },
    beforeRouteEnter(to, from, next) {
      // console.log(to)
      // console.log(from)
      next(vm => {
        vm.initBeforeRoute(vm, to, from)
      })
    },
    beforeRouteUpdate(to, from, next) {
      // console.log(to)
      // console.log(from)
      this.initBeforeRoute(this, to, from)
      next()
    }
  }
</script>

<style lang="scss" scoped>
</style>
